/**
 * InputManager 演示类
 * 展示如何使用InputManager进行键盘和触摸控制
 */

import { InputManager, InputAction } from './InputManager'

export class InputManagerDemo {
  private inputManager: InputManager
  private canvas: HTMLCanvasElement
  private ctx: CanvasRenderingContext2D
  private playerX: number = 400
  private playerY: number = 300
  private playerSize: number = 50
  private isJumping: boolean = false
  private isSliding: boolean = false
  private jumpVelocity: number = 0
  private gravity: number = 0.8
  private groundY: number = 300
  private animationId: number | null = null

  constructor(canvasId: string) {
    // 获取Canvas元素
    this.canvas = document.getElementById(canvasId) as HTMLCanvasElement
    if (!this.canvas) {
      throw new Error(`Canvas element with id "${canvasId}" not found`)
    }

    const context = this.canvas.getContext('2d')
    if (!context) {
      throw new Error('Failed to get 2D rendering context')
    }
    this.ctx = context

    // 设置Canvas尺寸
    this.canvas.width = 800
    this.canvas.height = 400

    // 初始化InputManager
    this.inputManager = new InputManager({
      element: this.canvas,
      enableTouch: true,
      swipeMinDistance: 30,
      tapMaxDuration: 200
    })

    // 设置输入处理器
    this.setupInputHandlers()

    // 开始游戏循环
    this.gameLoop()

    console.log('InputManager演示已启动！')
    console.log('键盘控制：')
    console.log('- 空格键/W键/上箭头：跳跃')
    console.log('- S键/下箭头：滑铲')
    console.log('- A键/左箭头：左移')
    console.log('- D键/右箭头：右移')
    console.log('- P键/ESC键：暂停')
    console.log('')
    console.log('触摸控制：')
    console.log('- 点击：跳跃')
    console.log('- 向上滑动：跳跃')
    console.log('- 向下滑动：滑铲')
    console.log('- 向左滑动：左移')
    console.log('- 向右滑动：右移')
    console.log('- 长按：暂停')
  }

  /**
   * 设置输入处理器
   */
  private setupInputHandlers(): void {
    this.inputManager.addHandler((action: InputAction, pressed: boolean) => {
      if (!pressed) return // 只处理按键按下事件

      switch (action) {
        case InputAction.JUMP:
          this.jump()
          console.log('跳跃！')
          break
        case InputAction.SLIDE:
          this.slide()
          console.log('滑铲！')
          break
        case InputAction.MOVE_LEFT:
          this.moveLeft()
          console.log('左移！')
          break
        case InputAction.MOVE_RIGHT:
          this.moveRight()
          console.log('右移！')
          break
        case InputAction.PAUSE:
          this.togglePause()
          console.log('暂停切换！')
          break
      }
    })
  }

  /**
   * 跳跃
   */
  private jump(): void {
    if (!this.isJumping && !this.isSliding) {
      this.isJumping = true
      this.jumpVelocity = -15
    }
  }

  /**
   * 滑铲
   */
  private slide(): void {
    if (!this.isSliding && !this.isJumping) {
      this.isSliding = true
      setTimeout(() => {
        this.isSliding = false
      }, 500)
    }
  }

  /**
   * 左移
   */
  private moveLeft(): void {
    this.playerX = Math.max(25, this.playerX - 50)
  }

  /**
   * 右移
   */
  private moveRight(): void {
    this.playerX = Math.min(this.canvas.width - 25, this.playerX + 50)
  }

  /**
   * 切换暂停
   */
  private togglePause(): void {
    if (this.animationId) {
      cancelAnimationFrame(this.animationId)
      this.animationId = null
      console.log('游戏暂停')
    } else {
      this.gameLoop()
      console.log('游戏恢复')
    }
  }

  /**
   * 游戏循环
   */
  private gameLoop(): void {
    this.update()
    this.render()
    this.animationId = requestAnimationFrame(() => this.gameLoop())
  }

  /**
   * 更新游戏逻辑
   */
  private update(): void {
    // 处理跳跃物理
    if (this.isJumping) {
      this.playerY += this.jumpVelocity
      this.jumpVelocity += this.gravity

      // 检查是否落地
      if (this.playerY >= this.groundY) {
        this.playerY = this.groundY
        this.isJumping = false
        this.jumpVelocity = 0
      }
    }
  }

  /**
   * 渲染游戏画面
   */
  private render(): void {
    // 清空画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)

    // 绘制地面
    this.ctx.fillStyle = '#8B4513'
    this.ctx.fillRect(0, this.groundY + this.playerSize, this.canvas.width, this.canvas.height - this.groundY - this.playerSize)

    // 绘制玩家
    const playerHeight = this.isSliding ? this.playerSize * 0.5 : this.playerSize
    const playerY = this.isSliding ? this.playerY + this.playerSize * 0.5 : this.playerY

    if (this.isJumping) {
      this.ctx.fillStyle = '#2196F3' // 蓝色（跳跃）
    } else if (this.isSliding) {
      this.ctx.fillStyle = '#FF9800' // 橙色（滑铲）
    } else {
      this.ctx.fillStyle = '#4CAF50' // 绿色（跑步）
    }

    this.ctx.fillRect(
      this.playerX - this.playerSize / 2,
      playerY,
      this.playerSize,
      playerHeight
    )

    // 绘制控制说明
    this.ctx.fillStyle = '#000000'
    this.ctx.font = '16px Arial'
    this.ctx.fillText('键盘: 空格/W-跳跃, S-滑铲, A/D-移动, P-暂停', 10, 30)
    this.ctx.fillText('触摸: 点击-跳跃, 滑动-控制, 长按-暂停', 10, 50)

    // 显示当前状态
    let status = '跑步'
    if (this.isJumping) status = '跳跃'
    else if (this.isSliding) status = '滑铲'
    
    this.ctx.fillText(`状态: ${status}`, 10, this.canvas.height - 20)
  }

  /**
   * 销毁演示
   */
  destroy(): void {
    if (this.animationId) {
      cancelAnimationFrame(this.animationId)
    }
    this.inputManager.destroy()
    console.log('InputManager演示已销毁')
  }
}